using System;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using EnvDTE80;

namespace TeamReview.Replay
{
	internal sealed class LineNumbersLink : ReplayLink
	{
	    public LineNumbersLink(DTE2 applicationObject) : base(applicationObject)
	    {
	    }

	    public override ReplayReceipt TryShowReplay(WorkItem workItem, DTE2 applicationObject)
		{
			ReplayReceipt receipt = new ReplayReceipt();

			string fileName = AbsoluteCodeFilePath(workItem);
			object snippetObject = workItem.Fields[Constants.CODE_SNIPPET_FIELD].Value;
			object startObject = workItem.Fields[Constants.CODE_START_LINE_FIELD].Value;
			object endObject = workItem.Fields[Constants.CODE_END_LINE_FIELD].Value;

			if (String.IsNullOrEmpty(fileName) || !System.IO.File.Exists(fileName) || snippetObject == null 
                || startObject == null || endObject == null)
				return receipt;

			string snippet = snippetObject.ToString();
			string startString = startObject.ToString();
			string endString = endObject.ToString();

			int start;
			int end;

			if (String.IsNullOrEmpty(startString) || Int32.TryParse(startString, out start) == false)
				return receipt;

			if (String.IsNullOrEmpty(endString) || Int32.TryParse(endString, out end) == false)
				return receipt;


			EnvDTE.Document document = applicationObject.Documents.Open(fileName, "Auto", false);
			if (document == null)
				return receipt;

			EnvDTE.TextDocument td = (EnvDTE.TextDocument)document.Object("");

			if (td == null || td.Selection == null || end > td.EndPoint.Line)
				return receipt;
			
			td.Selection.GotoLine(start, false);
			EnvDTE.EditPoint startPoint = td.CreateEditPoint(td.Selection.ActivePoint);
			td.Selection.GotoLine(end, true);
			EnvDTE.EditPoint endPoint = td.CreateEditPoint(td.Selection.ActivePoint);
			td.Selection.MoveToPoint(startPoint, false);
			td.Selection.MoveToPoint(endPoint, true);
			receipt.Selection = td.Selection;
			FindCodeSnippet(receipt, snippet, "Review Item found by original line numbers");
			HighlightCodeSnippet(receipt);

			return receipt;
		}
	}
}
